import React, { FC, useEffect, useRef, useState } from "react";
import Button from "../Button";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import classNames from "classnames";
export interface CalendarProps {
  value?: Date;
  range?: [Date, Date];
}
export type CalendarDateType =
  | "prev-month"
  | "next-month"
  | "prev-year"
  | "next-year"
  | "today";
export type CalendarDateCellType = "prev" | "current" | "next";
export type CalendarDateCell = {
  type: CalendarDateCellType;
  text: number;
};
const Calendar = (props: CalendarProps) => {
  let { value } = props;
  dayjs.locale("zh-cn");
  const firstDayOfWeek = dayjs().startOf("week").day();
  let now = dayjs();
  const [weekDays, setWeekDays] = useState([] as string[]);
  const [date, setDate] = useState(now);
  const [rows, setRows] = useState<CalendarDateCell[][] | null>(null);
  const weekMaping = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ] as const;

  useEffect(() => {
    if (!value) {
      setDate(dayjs(now));
    } else {
      setDate(dayjs(value));
    }
  }, [value]);

  useEffect(() => {
    let list: CalendarDateCell[] = [];
    const firstDay = date.startOf("month").day();
    const lastDay = date.subtract(1, "month").endOf("month").date();
    const count = firstDay - firstDayOfWeek;
    const preMonthDays: CalendarDateCell[] = Array.from({ length: count })
      .map((_, idx) => lastDay - (count - idx - 1))
      .map((_) => ({ text: _, type: "prev" }));
    const days = date.daysInMonth();
    const currentMonthDays: CalendarDateCell[] = Array.from({
      length: days,
    }).map((_, idx) => ({
      text: idx + 1,
      type: "current",
    }));

    list = [...preMonthDays, ...currentMonthDays];
    let remaining = 42 - list.length;
    const nextMonthDays: CalendarDateCell[] = Array.from({
      length: remaining,
    }).map((_, idx) => ({ text: idx + 1, type: "next" }));
    list.push(...nextMonthDays);

    let a = Array.from({ length: 6 }).map((_, idx) => {
      const start = idx * 7;
      return list.slice(start, start + 7);
    });
    setRows(() => a);
  }, [date]);

  useEffect(() => {
    setWeekDays(() => {
      return [
        ...weekMaping.slice(firstDayOfWeek),
        ...weekMaping.slice(0, firstDayOfWeek),
      ];
    });
  }, []);

  const selectDate = (type: CalendarDateType) => {
    const dateMap = {
      "prev-month": date.subtract(1, "month").date(1),
      "next-month": date.add(1, "month").date(1),
      "prev-year": date.subtract(1, "year").date(1),
      "next-year": date.add(1, "month").date(1),
      today: now,
    };

    const day = dateMap[type];
    setDate(() => day);
  };
  const formatter = (text: number, type: CalendarDateCellType) => {
    switch (type) {
      case "current":
        return dayjs(date).date(text);
      case "next":
        return dayjs(date).add(1, "month").date(text);
      case "prev":
        return dayjs(date).subtract(1, "month").date(text);
    }
  };
  const handlePick = ({ text, type }: CalendarDateCell) => {
    let day = formatter(text, type);
    setDate(() => day);
  };

  function getCurrentDate({ text, type }: CalendarDateCell): string {
    let day = formatter(text, type);
    const classes = classNames(type, {
      isSelect: day.isSame(date, "day"),
    });
    return classes;
  }
  return (
    <div className="coerger-calendar">
      <div className="header">
        <div className="title">{date ? date.format("YYYY-MM-DD") : ""}</div>
        <div className="button-group">
          <Button
            onClick={() => {
              selectDate("prev-year");
            }}
          >
            前一年
          </Button>
          <Button
            onClick={() => {
              selectDate("prev-month");
            }}
          >
            上个月
          </Button>
          <Button
            onClick={() => {
              selectDate("today");
            }}
          >
            今天
          </Button>
          <Button
            onClick={() => {
              selectDate("next-month");
            }}
          >
            下个月
          </Button>
          <Button
            onClick={() => {
              selectDate("next-year");
            }}
          >
            下一年
          </Button>
        </div>
      </div>
      <div className="content">
        <table>
          <thead>
            <tr>
              {weekDays.map((item, index) => (
                <th key={index}>{item}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows?.map((row, rid) => {
              return (
                <tr key={rid}>
                  {row.map((cell, cid) => {
                    return (
                      <td
                        key={cid}
                        onClick={() => handlePick(cell)}
                        className={getCurrentDate(cell)}
                      >
                        <div className="cell">
                          <div className="text">{cell.text}</div>
                        </div>
                      </td>
                    );
                  })}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default Calendar;
